package com.cqyanyu.yanyu.view;

import android.annotation.TargetApi;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.os.Build;
import android.util.AttributeSet;
import android.widget.ProgressBar;

/**
 * Created by cheng on 2016/6/14.
 */
public class ProgressBarTextView extends ProgressBar {
    public ProgressBarTextView(Context context) {
        super(context);

    }

    public ProgressBarTextView(Context context, AttributeSet attrs) {
        super(context, attrs);

    }

    public ProgressBarTextView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    public ProgressBarTextView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);

    }

    @Override
    protected synchronized void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        Paint paint = new Paint();
        String text = getProgress() + "%";
        int width = getWidth(text, 0, text.length(), paint);
        int hight = getHeight(paint);
        canvas.drawText(text, 0, text.length(), (canvas.getWidth() - width) / 2, (canvas.getHeight() - hight) / 2, paint);
    }

    private int getHeight(Paint paint) {
        Paint.FontMetrics fm = paint.getFontMetrics();
        return (int) Math.ceil(fm.descent - fm.ascent);
    }

    private int getWidth(String text, int i, int length, Paint paint) {
        return Math.round(paint.measureText(text, i, length));
    }


}
